package org.apache.rocketmq.common;

import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public abstract class ConfigManager {
    private static final Logger log = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);

    //从本地文件中加载数据方法
    public boolean load(){
        String fileName = null;
        try {
            fileName = configFilePath();
            String jsonStr = MixAll.file2String(fileName);
            if (jsonStr == null || jsonStr.length() == 0){
                return this.loadBak();
            }else{
                this.decode(jsonStr);
                log.info("load config file OK, {}",fileName);
                return true;
            }
        }catch (Exception e){
            log.error("load file error, file name: " + fileName, e);
            return this.loadBak();
        }
    }


    private boolean loadBak() {
        String fileName = null;
        try {
            fileName = this.configFilePath();
            String jsonString = MixAll.file2String(fileName + ".bak");
            if (jsonString != null && jsonString.length() > 0) {
                this.decode(jsonString);
                log.info("load " + fileName + " OK");
                return true;
            }
        } catch (Exception e) {
            log.error("load " + fileName + " Failed", e);
            return false;
        }

        return true;
    }

    public synchronized <T> void persist(String topicName, T t) {
        // stub for future
        this.persist();
    }

    public synchronized <T> void persist(Map<String, T> m) {
        // stub for future
        this.persist();
    }


    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @date:2025/1/17
     * @方法描述：把数据持久化到本地文件中的方法
     */
    public synchronized void persist() {
        //调用子类方法，对要持久化的数据进行编码
        String jsonString = this.encode(true);
        if (jsonString != null) {
            //得到文件路径
            String fileName = this.configFilePath();
            try {//在这里把数据写入到本地文件中
                MixAll.string2File(jsonString, fileName);
            } catch (IOException e) {
                log.error("persist file " + fileName + " exception", e);
            }
        }
    }

    protected void decode0(final byte[] key, final byte[] body) {

    }

    public boolean stop() {
        return true;
    }

    public abstract String configFilePath();

    public abstract String encode();

    public abstract String encode(final boolean prettyFormat);

    public abstract void decode(final String jsonString);

//    public Statistics getStatistics() {
//        return rocksDBConfigManager == null ? null : rocksDBConfigManager.getStatistics();
//    }
}